from flask import (
    Blueprint,
    request,
    g,
)

from utils import restful, api_util, common_util
from datetime import datetime, date
from apps.api.decorators import *
from .models import User, UserRecord, UserDevice
from .forms import UploadImgForm
from apps.common.models import *
from apps.mall.models import *
from exit import db
from decimal import Decimal
from sqlalchemy import func, or_


bp = Blueprint("index", __name__, url_prefix="/index")


@bp.route('/index/')    # 首页
@login_required_query
def index():
    index_dict = dict()
    return restful.success(data=index_dict)


@bp.route('/get_user_team/', methods=['POST'])  # 团队接口
@login_required_query
def get_user_team():
    page = request.form.get('page', type=int, default=1)
    pages = (page - 1) * 10
    user_id = request.form.get('user_id')
    if not user_id:
        return restful.params_error(message='请传入参数')
    # if g.user.id != user_id:
    #     return restful.params_error(message='只能看下级')
    user = User.query.get(user_id)
    if not user:
        return restful.params_error(message='没有找到用户')
    team_json = user.team_json()
    # if user.id != g.user.id:
    #     return restful.params_error(message='权限不足')
    team_list = list()
    parent_obj = User.query.filter_by(p_id=user.id).order_by(User.create_time)
    user_parent = parent_obj.limit(10).offset(pages)

    # 直推和团队
    # direct_buy = db.session.query(func.sum(User.user_buy)).filter_by(p_id=user.id).scalar()
    # if direct_buy is None:
    #     direct_buy = 0
    # team_json['direct_buy'] = '{}'.format(direct_buy + user.user_buy)
    # team_json['team_buy'] = '{}'.format(user.team_buy)

    # team_json['info_str'] = '分享业绩{}'.format(user.team_buy)
    team_json['info_str'] = '{}'.format(user.nickname)
    team_json['num_str'] = '团队{}    团队业绩{}'.format(user.team_num, user.team_buy)
    for i in user_parent:
        parent_json = i.team_json()
        # parent_level = api_util.level_str(i.h_level)
        # parent_json['info_str'] = '分享业绩{}'.format(i.team_buy)
        parent_json['info_str'] = '{}'.format(i.nickname)
        parent_json['num_str'] = '团队{}    团队业绩{}'.format(i.team_num, i.team_buy)

        # direct_buy = db.session.query(func.sum(User.user_buy)).filter_by(p_id=i.id).scalar()
        # if direct_buy is None:
        #     direct_buy = 0
        # parent_json['direct_buy'] = '{}'.format(direct_buy + i.user_buy)
        # parent_json['team_buy'] = '{}'.format(i.team_buy)
        team_list.append(parent_json)
    team_json['sub_list'] = team_list
    return restful.success(data=team_json)


@bp.route('/get_user_direct/', methods=['POST'])
@login_required_query
def get_user_direct():
    page = request.form.get('page', type=int, default=1)
    pages = (page - 1) * 10
    sub_user = User.query.filter_by(rp_id=g.user.id).limit(10).offset(pages)
    team_list = list()
    for i in sub_user:
        parent_json = i.team_json()
        # parent_json['username'] = i.username
        parent_json['info_str'] = '{}'.format(i.username)
        p_user = User.query.filter_by(id=i.p_id).first()
        parent_json['p_name'] = p_user.username
        parent_json['num_str'] = '会员{}    团队业绩{}'.format(i.direct_num, i.team_buy)
        team_list.append(parent_json)
    team_json = dict()
    team_json['sub_list'] = team_list
    return restful.success(data=team_json)


@bp.route('/api_test/')
def api_test():
    return restful.success()


@bp.route('/get_update/', methods=['POST'])
@login_need
def get_update():
    state_0 = 0    # 正常
    state_1 = 1    # 更新
    state_2 = 2    # 维护
    data = dict()
    data['url'] = ''
    data['state'] = state_0
    return restful.success(data=data, message='网络错误')
    device = request.form.get('device')
    version = request.form.get('version')
    if not (device and version):
        return restful.params_error(message='请传入参数!')
    version = int(version)
    if device == 'android':
        if version >= 10:
            data['state'] = state_0
            return restful.success(data=data)
        else:
            data['state'] = state_1
            data['url'] = 'http://39.105.141.79/d/zmtb.apk'
            return restful.success(data=data)
    elif device == 'iOS':
        if version >= 1:
            data['state'] = state_0
            return restful.success(data=data)
        else:
            data['state'] = state_1
            data['url'] = ''
            return restful.success(data=data, message='请立即更新！')
    else:
        return restful.params_error(message='参数不合法!')


@bp.route('/common_img/')  # 公告展示
@login_required_query
def common_img():
    img_dict = dict()
    push_list = list()
    push_dict0 = dict()
    push_dict0['big_img'] = ''
    push_dict0['small_img'] = ''
    push_dict0['title'] = ''
    push_dict0['url'] = ''
    # push_list.append(push_dict0)
    img_dict['img_list'] = push_list

    return restful.success(data=img_dict)


@bp.route('/notice/')
@login_required_query
def notice():
    notice_list = [
        {
            'text': '在线拍卖交易，价高者得，请自行把控涨跌风险！',
            'url': '',
            'img': ''
        },
        {
            'text': '甘肃省文化产权交易中心是经中宣部批复同意、甘肃省人民政府批准设立的省内唯一进行文化产权交易的国资平台机构',
            'url': '',
            'img': ''
        }
    ]

    data_dict = dict()
    data_dict['notice_list'] = notice_list
    return restful.success(data=data_dict)


@bp.route('/article_info/')   # 资讯信息
# @login_required
def article_info():
    article = Article.query.order_by(Article.article_time.desc()).all()
    article_list = list()
    for i in article:
        info = i.article_json()
        article_list.append(info)
    data_dict = dict()
    data_dict['article_list'] = article_list
    return restful.success(data=data_dict)


